import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './coupons.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import icon_coupon_expired from '@/assets/icon_coupon_expired.png'
import icon_coupon_used from "@/assets/icon_coupon_used.png"

import NavigateBar from "@/components/NavigateBar";
import { getCoinInfo, isUnvalidUserInfo } from "@/utils/storage";
import { LangThai } from '@/utils/langThai';
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import CheckInDialog from "@/components/CheckInDialog/CheckInDialog";
import { couponUse, couponVerify, getCouponList } from "@/store/actions/coupons";
import { toFinanceString } from "@/utils/utils";

/**
 * 优惠券页
 */
export default function Coupons() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    //显示check in弹框
    const [checkInMaskVisible, setCheckInMaskVisible] = useState(false);

    // 当前输入coupon code
    const [couponCode, setCouponCode] = useState("");
    const [couponCodeError, setCouponCodeError] = useState(null);

    // coupon list
    const [couponList, setCouponList] = useState([]);

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //router

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        // 判断是否需要重登录
        if (isUnvalidUserInfo()) {
            history.replace('/login')
            return
        }

        // 读取缓存
        // const coinInfo = getCoinInfo();
        // let gCoinInfo = { ...coinInfo };
        // setCurCoinInfo(gCoinInfo);

        // 获取coupons
        doGetCoupons();

        //打点
        doHitEvent("NEW_COMER_ENJOY_START")

        return () => {
            //打点
            // doHitEvent("NEW_COMER_ENJOY_END")
        }
    }, [])

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const initCouponList = () => {
        let list = [];
        list.push({
            amount: "500",
            condition: "Available when balance ≥5000 ¢",
            expired: "Expired until dd/mm/yy",
            status: "1"
        });

        list.push({
            amount: "500",
            condition: "Available when balance ≥5000 ¢",
            expired: "Expired until dd/mm/yy",
            status: "2"
        });

        list.push({
            amount: "500",
            condition: "Available when balance ≥5000 ¢",
            expired: "Expired until dd/mm/yy",
            status: "3"
        });

        list.push({
            amount: "500",
            condition: "Available when balance ≥5000 ¢",
            expired: "Expired until dd/mm/yy",
            status: "3"
        });

        setCouponList(list);
    }

    const onHandleInputChanged = (e) => {
        setCouponCode(e.target.value);
    }

    const onHandleCouponVerify = () => {
        if (!couponCode) {
            setCouponCodeError(curLang.coupon5);
            return;
        }
        if (couponCode.length <= 0) {
            setCouponCodeError(curLang.coupon5);
            return;
        }
        setCouponCodeError(null);

        // coupon verify
        doCouponVerify(couponCode);
    }

    const onHandleCouponUse = (cashCouponId) => {
        if (!cashCouponId) {
            return;
        }
        if (cashCouponId.length <= 0) {
            return;
        }

        // coupon use
        doCouponUse(cashCouponId);
    }

    // 获取coupons
    const doGetCoupons = async () => {
        console.log("doGetCoupons: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getCouponList(onDoGetCouponsCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const doCouponVerify = async (code) => {
        console.log("doCouponVerify: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = couponVerify(code, onDoCouponVerifyCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    const doCouponUse = async (cashCouponId) => {
        console.log("doCouponUse: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = couponUse(cashCouponId, onDoCouponUseCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取coupons 返回
    const onDoGetCouponsCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取coupons 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            setCouponList(data || []);

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // coupon verfiy 返回
    const onDoCouponVerifyCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('coupon verify 返回: ' + success);

        if (success) {
            // 处理流程业务
            doGetCoupons();

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };

    // coupon use 返回
    const onDoCouponUseCallback = (success, data, isNeedToReLogin) => {
        //关闭loading
        setMaskVisible(false)
        console.log('coupon use 返回: ' + success);

        if (success) {
            // 处理流程业务
            doGetCoupons();

        } else {
            if (isNeedToReLogin) {
                history.replace('/login')
            }
        }
    };


    return (
        <div className={styles.couponRoot}>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.coupon1}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFull pageContentPaddingHorizontal16px">

                {/* 验证 coupon code 模块 */}
                <div className={styles.couponSectionContent}>
                    <div className={styles.couponCodeTitle}>{curLang.coupon2}</div>

                    <input
                        className={styles.couponCodeInput}
                        placeholder={curLang.coupon3}
                        type="text"
                        value={couponCode}
                        onChange={e => onHandleInputChanged(e)}
                        autoComplete="off" />

                    {couponCodeError && <div className={styles.couponCodeError}>{curLang.coupon5}</div>}
                </div>

                <div className={styles.couponCodeVerify} onClick={() => { onHandleCouponVerify() }}>{curLang.coupon4}</div>

                {couponList.length && couponList.length > 0 && <div className={styles.couponListTable}>
                    {couponList.map((value, index) => {
                        if (value.status === 'CREATED') {
                            if (value.useFlag === true) {
                                return <div className={styles.couponContentMode1} key={index}>
                                    <div className={styles.couponTag}>{value.tag}</div>
                                    <div className={styles.couponAmountContent}>
                                        <div className={styles.couponAmount}>{toFinanceString(value.amount)}</div>
                                        <div className={styles.couponStatusEnable} onClick={() => { onHandleCouponUse(value.id + "") }}>{curLang.coupon8}</div>
                                    </div>
                                    <div className={styles.couponConditionWhite}>{value.condition}</div>
                                    <div className={styles.couponExpired}>{curLang.coupon7}{value.expiredDate}</div>
                                </div>

                            } else {
                                return <div className={styles.couponContentMode2} key={index}>
                                    <div className={styles.couponTagWhite}>{value.tag}</div>
                                    <div className={styles.couponAmountContent}>
                                        <div className={styles.couponAmount}>{toFinanceString(value.amount)}</div>
                                        <div className={styles.couponStatusDisable} onClick={() => { Toast.show(curLang.coupon9); }}>{curLang.coupon8}</div>
                                    </div>
                                    <div className={styles.couponConditionRed}>{value.condition}</div>
                                    <div className={styles.couponExpired}>{curLang.coupon7}{value.expiredDate}</div>
                                </div>
                            }

                        } else if (value.status === 'EXPIRED') {
                            return <div className={styles.couponContentMode3} key={index}>
                                <div className={styles.couponTagDisable}>{value.tag}</div>
                                <div className={styles.couponAmountContent}>
                                    <div className={styles.couponAmount}>{toFinanceString(value.amount)}</div>
                                </div>
                                <div className={styles.couponConditionWhite}>{value.condition}</div>
                                <div className={styles.couponExpired}>{curLang.coupon7}{value.expiredDate}</div>
                                <img className={styles.couponIconExpired} src={icon_coupon_expired} alt="" />
                            </div>

                        } else if (value.status === 'USED') {
                            return <div className={styles.couponContentMode3} key={index}>
                                <div className={styles.couponTagDisable}>{value.tag}</div>
                                <div className={styles.couponAmount}>{toFinanceString(value.amount)}</div>
                                <div className={styles.couponConditionWhite}>{value.condition}</div>
                                <div className={styles.couponExpired}>{curLang.coupon7}{value.expired}</div>
                                <img className={styles.couponIconExpired} src={icon_coupon_used} alt="" />
                            </div>

                        } else {
                            return <div></div>
                        }
                    })}
                </div>}
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>

            {/* 签到提示 */}
            <CheckInDialog visible={checkInMaskVisible} onConfirm={() => { setCheckInMaskVisible(false) }}></CheckInDialog>

        </div >
    )
}